import {
	baseUrl
} from './config.js'
import {
	login,
	getopenid
} from '../apis/login';

function http(url, data = {}, method = 'POST', showLoading = false, contentType = 'application/x-www-form-urlencoded') {
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				mask: true
			})
		}
		let header = {
			'content-Type': contentType
		}
		if (uni.getStorageSync('userinfo') != '') {
			header = {
				'content-Type': contentType,
				'ooh-auth': "bearer " + uni.getStorageSync('userinfo').jwt.access_token
			}
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header: header,
			success(res) {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				if (res.data.errcode === 401) {
					//先执行一次自动登录，成功则继续请求，失败则调整首页
					userlogin(url, data, method, showLoading, contentType).then(result => {
						if (result.errcode) {
							uni.showToast({
								title: '请先登录',
								icon: 'none',
								duration: 3000
							})
							uni.clearStorageSync()
							setTimeout(function() {
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}, 1500)
							reject(res.data)
						} else {
							http(url, data, method, showLoading, contentType).then(newRes => {
								resolve(newRes)
							})
						}

					})

				} else {
					resolve(res.data)
				}
			},
			fail(res) {
				uni.showToast({
					title: '连接服务器失败,请稍后重试!',
					icon: 'none',
					duration: 3000
				})
				uni.hideLoading()
			}
		})
	})

}
export default http;

async function userlogin(url, data, method, showLoading, contentType) {
	var openId = uni.getStorageSync('openId')
	if (!openId) {
		// 登录
		let code = (await uni.login()).code;
		openId = (await getopenid({
			appid: 'wx511728e8c5850f0b',
			code: code
		})).openid;
		uni.setStorageSync('openid', openId)
	}
	let result = await login({
		appid: 'wx511728e8c5850f0b',
		openid: openId
	});

	if (result.errcode) {
		uni.showToast({
			title: '请先登录',
			icon: 'none',
			duration: 3000
		})
		uni.clearStorageSync()
		setTimeout(function() {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}, 1500)
	} else {
		uni.setStorageSync('userinfo', result)

	}


	return result
	// if (result.errcode) {
	// 	uni.showToast({
	// 		title: '请先登录',
	// 		icon: 'none',
	// 		duration: 3000
	// 	})
	// 	uni.clearStorageSync()
	// 	setTimeout(function() {
	// 		uni.reLaunch({
	// 			url: '/pages/index/index'
	// 		})
	// 	}, 1500)
	// 	reject(res.data)
	// } else {
	// 	uni.setStorageSync('userinfo', result)
	// 	Request(url, data, method, showLoading, contentType)
	// }

}